﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RemoteImaging.LicensePlate;

namespace RemoteImaging
{
    class SuspectCarChecker : ILicensePlateObserver
    {
        private static NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        private System.Collections.Concurrent.BlockingCollection<string> _plateNumbersToCheck
            = new BlockingCollection<string>();

        private Task _thread;


        public SuspectCarChecker(ILicensePlateEventPublisher licensePlateEventPublisher)
        {
            _thread = Task.Factory.StartNew(WorkerThread, null, TaskCreationOptions.LongRunning);
            licensePlateEventPublisher.RegisterForLicensePlateEvent(this);
        }
        public void LicensePlateCaptured(LicensePlateInfo licensePlateInfo)
        {
            if (_plateNumbersToCheck.Count > 100)
            {
                Logger.Warn("盗抢车辆检查线程处理速度过慢，已经超过100条等待检查，丢弃当前车辆{0}", licensePlateInfo.LicensePlateNumber);
                return;
            }

            if (!string.IsNullOrEmpty(licensePlateInfo.LicensePlateNumber))
            {
                _plateNumbersToCheck.Add(licensePlateInfo.LicensePlateNumber);
            }
        }


        private void WorkerThread(object state)
        {
            Logger.Info("被盗车辆检查线程开始工作...");
            foreach (var plateNumber in _plateNumbersToCheck.GetConsumingEnumerable())
            {
                try
                {
                    Logger.Trace("开始检查'{0}'是否是盗抢车辆", plateNumber);
                    var isSuspectCar = SuspectCarService.IsSuspectCar(plateNumber);
                    Logger.Trace("'{0}'是盗抢车辆检查结果：{1}", plateNumber, isSuspectCar);
                    if (isSuspectCar)
                    {
                        var message = string.Format("在{0}发现疑似盗抢车辆(车牌号:{1})，请通知相关人员前往检查",
                            Properties.Settings.Default.HostName,
                            plateNumber);
                        SuspectCarService.SendSms(message);
                    }

                }
                catch (Exception ex)
                {
                    Logger.ErrorException("盗抢车辆检查线程发生异常", ex);
                }
            }

        }
    }
}
